package com.mdnote.jianzhi_offer.array;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/11/10 0:19
 * @Email rhythm_2019@163.com
 * @Description 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
 */
public class Offer21 {

    public int[] exchange(int[] nums) {
        if (nums == null || nums.length == 0) {
            return new int[0];
        }

        int left = 0, right = nums.length - 1;
        while (left < right) {
            while (left < right && !judge(nums, left)) {
                // 走到偶数
                left++;
            }
            while (left < right && judge(nums, right)) {
                // 走到奇数
                right--;
            }
            // System.out.println(left + " " + right);
            swap(nums, left, right);
            left++;
            right--;
        }
        return nums;
    }

    private void swap(int[] nums, int idx1, int idx2) {
        int tmp = nums[idx1];
        nums[idx1] = nums[idx2];
        nums[idx2] = tmp;
    }

    private boolean judge(int[] nums, int idx) {
        return (nums[idx] & 1) == 0;
    }
}
